package testJdk.commonUse.collections.concurrent_coll;

import lombok.SneakyThrows;
import org.junit.Test;
import testJdk.thread.pool.SinglePoolUtil;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

/**
 * @ClassName : learn_jdk.commonUse.collections.concurrent_coll.ConcurrentCollectionTest
 * @Description : 测试线程安全的集合
 * Created by cyd on 2021-10-23 22:55:50
 */
public class ConcurrentCollectionTest {

    @Test
    public void test01() throws InterruptedException {
        List<Object> list = new ArrayList<>();
        // 转化成线程安全的集合
        List<Object> synchronizedList = Collections.synchronizedList(list);

        ExecutorService threadPool = SinglePoolUtil.getThreadPool();
        CountDownLatch countDownLatch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            threadPool.execute(() -> {
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                synchronizedList.add(finalI);
                countDownLatch.countDown();
            });
        }
        System.out.println("直接输出synchronizedList:" + synchronizedList);
        countDownLatch.await();
        System.out.println("10个线程执行完毕后:" + synchronizedList);
    }


    @Test
    public void test02() throws InterruptedException {

        HelloRunnableTask hrt = new HelloRunnableTask();
        new Thread(hrt).start();
        Thread.sleep(2000);

    }

    @Test
    public void test03() {
        List<String> list = Collections.synchronizedList(new ArrayList<>());
        list.add("a");
        list.add("b");
        list.add("c");
        System.out.println(list);

        for (int i = 0; i < 10; i++) {
            list.add("" + i);
        }
        System.out.println(list);

        for (String s : list) {
            list.add(s.toUpperCase(Locale.ROOT));
        }
        System.out.println("over");

    }

    @Test
    public void test04() {
        ExecutorService threadPool = SinglePoolUtil.getThreadPool();
        threadPool.execute(() -> {
            test03();
        });
        System.out.println("这一句仍然执行，因为被终止的是抛出异常的线程01，" +
                "而不是开启01线程的线程");
    }
}


class HelloRunnableTask implements Runnable {

    public static List<String> list = Collections.synchronizedList(new ArrayList<>());

    static {
        list.add("a");
        list.add("b");
        list.add("c");
        System.out.println(list);

    }


    @SneakyThrows
    @Override
    public void run() {
        Thread.sleep(1000);
        ListIterator<String> iterator = list.listIterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            String s = next.toUpperCase(Locale.ROOT);
            System.out.println(next);

            list.add(s);
        }
    }
}
